package thread.wang_bao_ling.c35;

/**
 * @Auther: luobiao
 * @Date: 2020/7/23 07:50
 * @Description:
 */
public class Proxy {
    private boolean started = false;
    private volatile boolean terminated = false;
    //采集线程
    Thread rptThread;
    //启动采集功能
    synchronized void start(){
        //不允许同时启动多个采集线程
        if (started) {
            return;
        }
        started = true;
        rptThread = new Thread(()->{
            while (!terminated) {
                //省略采集、回传实现
                report();
                //每隔两秒钟采集、回传一次数据
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    System.out.println("监控线程被中断");
                    //在线程休眠时调用中断后中断标志会被清除，需再次中断
                    Thread.currentThread().interrupt();
                }
            }
            //执行到此处说明线程马上终止
            started = false;
        });
        rptThread.start();
    }
    //终止采集功能
    synchronized void stop(){
        terminated=true;
        rptThread.interrupt();
    }

    private void report(){
        System.out.println("数据回传中...");
    }
}
